package com.ruoyi.inspection.service.impl;

import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.inspection.config.QiNiuYunConfig;
import com.ruoyi.common.response.Result;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.inspection.service.QiNiuYunService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 七牛云的文件上传service业务层处理
 *
 * @author ruoyi
 * @date 2024-06-04
 */
@Service
public class QiNiuYunServiceImpl implements QiNiuYunService {
    @Autowired
    private QiNiuYunConfig qiNiuYunConfig;

    @Override
    public Result upload(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new RuntimeException("文件是空的");
        }
        // 创建上传token
        Auth auth = Auth.create(qiNiuYunConfig.getAccessKey(), qiNiuYunConfig.getSecretKey());
        String upToken = auth.uploadToken(qiNiuYunConfig.getBucket());

        // 设置上传配置，Region要与存储空间所属的存储区域保持一致
        Configuration cfg = new Configuration(Region.huadong());

        // 创建上传管理器
        UploadManager uploadManager = new UploadManager(cfg);

        String originalFilename = file.getOriginalFilename();
        // 构造文件目录和文件名
        assert originalFilename != null;
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileKey = qiNiuYunConfig.getMkdir() + IdUtils.generateQiNiuYunUUID() + suffix;

        // 上传文件
        Response response = uploadManager.put(file.getInputStream(), fileKey, upToken, null, null);

        if (response.isOK()) {
            return Result.success("上传成功", qiNiuYunConfig.getDomain() + fileKey);
        } else {
            return Result.error("上传失败");
        }
        // 返回文件url
//        return qiNiuYunConfig.getDomain() + fileKey;
    }
}
